package xiaolong.zhou.spring_demo.Service.achieve;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import xiaolong.zhou.spring_demo.Mapper.PriceLogMapper;
import xiaolong.zhou.spring_demo.Mapper.RealUserMapper;
import xiaolong.zhou.spring_demo.Mapper.UserMapper;

import xiaolong.zhou.spring_demo.Pojo.*;
import xiaolong.zhou.spring_demo.Service.Users;
import xiaolong.zhou.spring_demo.Utils.Result;
import xiaolong.zhou.spring_demo.Utils.Token;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Service
public class UserAchieve implements Users {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RealUserMapper realUserMapper;
    @Autowired
    private PriceLogMapper priceLogMapper;
    @Autowired
    private RabbitSend rabbitSend;

    /**
     * 列表实现
     *
     * @param page
     * @param size
     * @param username
     * @param phone
     * @param email
     * @return
     */
    @Override
    public Result lists(Integer page, Integer size, String username, String phone, String email) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        if (Optional.ofNullable(username).isPresent()) {
            queryWrapper.like("user", username);
        }
        if (Optional.ofNullable(phone).isPresent()) {
            queryWrapper.like("phone", phone);
        }
        if (Optional.ofNullable(email).isPresent()) {
            queryWrapper.like("email", email);
        }
        queryWrapper.eq("delete_time", "");
        PageHelper.startPage(page, size);
        List<User> lists = userMapper.selectList(queryWrapper);
        System.out.println(lists);
        Page<User> page1 = (Page<User>) lists;
        PageBen pageBen = new PageBen(page1.getTotal(), page1.getResult());
        return Result.success(pageBen);
    }

    /**
     * 详情具体实现
     *
     * @param id
     * @return
     */
    @Override
    public Result show(Integer id) {
        UserDetail user = userMapper.Detail(id);
        return Result.success(user);
    }

    /**
     * 添加用户具体实现
     *
     * @param relayUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public Result store(UserDetail userDetail) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", userDetail.getPhone());
        queryWrapper.eq("delete_time", "");
        Long userCount = userMapper.selectCount(queryWrapper);
        User user = new User();
        if (userCount > 0) {
            return Result.error("该手机号已注册");
        }
        user.setUser(userDetail.getUser());
        user.setPhone(userDetail.getPhone());
        user.setPrice((float) 0.00);
        user.setEmail(userDetail.getEmail());
        user.setPassword(DigestUtils.md5DigestAsHex(userDetail.getPassword().getBytes()));
        user.setAvatar(userDetail.getAvatar());
        user.setDeleteTime("");
        user.setCreateTime(new Date().toString());
        userMapper.insert(user);
        Integer userId = user.getId();

        RealUser realUser = new RealUser();
        realUser.setAge(userDetail.getAge());
        realUser.setUserId(userId);
        realUser.setSex(userDetail.getSex());
        realUser.setDocuments(userDetail.getDocuments());
        realUser.setRealName(userDetail.getRealName());
        realUser.setDeleteTime("");
        realUser.setCreateTime(new Date().toString());
        realUserMapper.insert(realUser);
        return Result.success();
    }

    /**
     * 修改用户具体实现
     *
     * @param userDetail
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public Result save(UserDetail userDetail) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", userDetail.getPhone());
        queryWrapper.eq("delete_time", "");
        User userInfo = userMapper.selectOne(queryWrapper);

        if (userInfo!=null && userInfo.getId() != userDetail.getId()) {
            return Result.error("该手机号已注册");
        }
        queryWrapper.clear();
        queryWrapper.eq("id",userDetail.getId());
        queryWrapper.eq("delete_time", "");
        User userInfos = userMapper.selectOne(queryWrapper);
        if(userInfos==null){
            return Result.error("用户不存在");
        }
        User user = new User();
        user.setUser(userDetail.getUser());
        user.setId(userDetail.getId());
        user.setPrice(userDetail.getPrice());
        user.setPhone(userDetail.getPhone());
        user.setEmail(userDetail.getEmail());
        if (userDetail.getPassword() != null && userDetail.getPassword() != "") {
            user.setPassword(DigestUtils.md5DigestAsHex(userDetail.getPassword().getBytes()));
        }
        user.setAvatar(userDetail.getAvatar());
        userMapper.updateById(user);

        RealUser realUser = new RealUser();
        realUser.setAge(userDetail.getAge());
        realUser.setSex(userDetail.getSex());
        realUser.setDocuments(userDetail.getDocuments());
        realUser.setRealName(userDetail.getRealName());
        realUser.setDeleteTime("");
        QueryWrapper<RealUser> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_id", userDetail.getId());
        queryWrapper1.eq("delete_time", "");
        RealUser realUserInfo = realUserMapper.selectOne(queryWrapper1);
        if (realUserInfo == null) {
            realUser.setUserId(userDetail.getId());
            realUserMapper.insert(realUser);
        } else {
            UpdateWrapper<RealUser> userUpdateWrapper = new UpdateWrapper<>();
            userUpdateWrapper.eq("user_id", userDetail.getId());
            realUserMapper.update(realUser, userUpdateWrapper);
        }

        return Result.success();

    }

    /**
     * 删除用户具体实现
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public Result delete(Integer id) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.eq("delete_time", "");
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            return Result.error("用户不存在或已被删除");
        }
        userMapper.Deleted(id);
        QueryWrapper<RealUser> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_id", id);
        queryWrapper1.eq("delete_time", "");
        Long realUserCount = realUserMapper.selectCount(queryWrapper1);
        System.out.println(realUserCount);
        if (realUserCount > 0) {
            realUserMapper.Deleted(id);
        }
        return Result.success();
    }

    /**
     * 用户余额充值具体实现
     *
     * @param recharge
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public Result recharge(Recharge recharge, HttpServletRequest request) {
        Map tokenUser = Token.getTokenInfo(request.getHeader("token"));//获取到当前用户的登录信息
        if (recharge.getPrice() < 0) {
           return Result.error("充值金额有误");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", tokenUser.get("id"));
        queryWrapper.eq("delete_time", "");
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            return Result.error("用户不存在或已被删除");
        }
        Float sumPrice = recharge.getPrice()+user.getPrice();
        System.out.println(sumPrice);

        PriceLog priceLog = new PriceLog();
        priceLog.setNewPrice(sumPrice);//改变前的余额
        priceLog.setOldPrice(user.getPrice());//改变后的余额
        priceLog.setPrice(recharge.getPrice());//充值金额
        priceLogMapper.insert(priceLog);

        Map<String,Object> rabbitData = new HashMap<>();
        rabbitData.put("price",recharge.getPrice());
        rabbitData.put("old_price",user.getPrice());
        rabbitData.put("new_price",sumPrice);
        rabbitData.put("email",user.getEmail());

        user.setPrice(sumPrice);//用户主表余额
        userMapper.update(user,queryWrapper);
        //向MQ发送消息推送邮箱信息
        rabbitSend.RechargeQueues("recharge-queues",rabbitData);

        return Result.success();
    }
}
